package gee

import (
	"log"
	"net/http"
)

type engine struct {
	router *router
}

func New() *engine {

	e := &engine{router: NewRouter()}

	e.Get("/favicon.ico", func(c *Context) {
		c.SetHeader("Content-Type", "image/gif")
		c.Data([]byte(""))
	})
	return e
}

func (e *engine) AddRouter(method string, path string, handler HandlerFunc) {

	e.router.AddRouter(method, path, handler)
}

func (e *engine) Get(path string, handler HandlerFunc) {

	e.router.AddRouter(http.MethodGet, path, handler)
}

func (e *engine) Post(path string, handler HandlerFunc) {

	e.router.AddRouter(http.MethodPost, path, handler)
}

func (e *engine) Run(addr string) {

	log.Printf("Start server at %s...\n", addr)
	err := http.ListenAndServe(addr, e)
	if err != nil {
		log.Fatalf("Start server failed: %s\n", err.Error())
	}
}

func (e *engine) ServeHTTP(rw http.ResponseWriter, r *http.Request) {

	c := NewContext(rw, r)
	e.router.Handle(c)
}
